/*
 * @Description: 表格设置
 * @Author: DHL
 * @Date: 2021-12-14 10:39:39
 * @LastEditors: DHL
 * @LastEditTime: 2024-02-04 11:45:39
 */

import { defineStore } from 'pinia'
import { store } from '@/store'
import { storageUtils } from '@/utils/storageUtils'
import { useLoginUserStore } from '@/store/modules/loginUser'
import { stringUtils } from '@/utils/stringUtils'
import { arrayRemoveByPropertyValue } from '@/utils/arrayUtils'
import { merge } from 'lodash-es'
import { apiUserConfigSaveOrUpdate } from '@/api/system/userConfig'
import { isNotEmpty } from '@/utils/isUtils'

const TABLE_SETTING_KEY = 'TW-TABLE-SETTING'

/**
 * 用户配置列
 * key：tableId
 * value：配置列
 */
interface ICustomColumn {
  [key: string]: Array<any>
}

/**
 * 用户表格配置
 */
export interface ITableSettingState {
  /**
   * 配置列
   */
  customColumn: ICustomColumn
}

const tableSettingStore = defineStore({
  id: 'tableSettingState',
  state: (): ITableSettingState => ({
    customColumn: {} as ICustomColumn
  }),
  getters: {},
  actions: {
    /**
     * 获取登录用户
     */
    getLoginName() {
      let loginName = useLoginUserStore().loginName
      if (stringUtils.isEmpty(loginName)) {
        loginName = 'defaultLoginName'
      }
      return loginName
    },

    /**
     * 构建表格配置
     */
    buildTableSettingAction(userConfig: any) {
      if (userConfig && userConfig.columnConfig) {
        this.setTableSetting(JSON.parse(userConfig.columnConfig) as ITableSettingState)
      } else {
        // 读取缓存配置
        const tableSettingList: Array<any> = storageUtils.getLocalItem(TABLE_SETTING_KEY)
        const loginName = this.getLoginName()

        if (tableSettingList && tableSettingList.length > 0) {
          let tableSetting: any = null

          tableSettingList.forEach((item) => {
            if (item.key === loginName) {
              tableSetting = item.value
            }
          })

          if (tableSetting) {
            this.setTableSetting(tableSetting as ITableSettingState)
          }
        }
      }
    },

    /**
     * 加载用户配置，并设置到系统
     * @param tableSetting
     */
    setTableSetting(tableSetting: ITableSettingState) {
      this.customColumn = tableSetting.customColumn
      this.saveTableSettingStorageAction()
    },

    /**
     * 列设置
     * @param customColumn
     */
    setCustomColumn(customColumn: ICustomColumn) {
      merge(this.customColumn, customColumn)
      this.saveTableSettingAction()
    },

    /**
     * 获取列设置
     */
    getCustomColumn(tableId: string) {
      if (this.customColumn) {
        return this.customColumn[tableId]
      }
      return []
    },

    /**
     * 删除列设置
     * @param tableId
     */
    removeCustomColumn(tableId: string) {
      delete this.customColumn[tableId]
      this.saveTableSettingAction()
    },

    /**
     * 获取配置
     * @returns
     */
    getTableSetting() {
      return {
        customColumn: this.customColumn
      }
    },

    /**
     * 将配置信息缓存到浏览器
     */
    saveTableSettingStorageAction() {
      const loginName = this.getLoginName()

      // 获取浏览器缓存数据
      let tableSettingList: Array<any> = storageUtils.getLocalItem(TABLE_SETTING_KEY)

      if (tableSettingList && tableSettingList.length > 0) {
        // 如果配置不为空，删除用户的配置
        arrayRemoveByPropertyValue(tableSettingList, 'key', loginName)

        tableSettingList.push({
          key: loginName,
          value: this.getTableSetting()
        })
      } else {
        tableSettingList = [
          {
            key: loginName,
            value: this.getTableSetting()
          }
        ]
      }

      // 配置缓存搭配浏览器
      storageUtils.setLocalItem({
        key: TABLE_SETTING_KEY,
        value: tableSettingList
      })
    },

    /**
     * 保存表格配置到数据库
     */
    saveTableSettingAction() {
      this.saveTableSettingStorageAction()

      const userId: string = useLoginUserStore().id || ''
      if (isNotEmpty(userId)) {
        apiUserConfigSaveOrUpdate({
          userId: userId,
          configJson: JSON.stringify(this.getTableSetting()),
          configType: '1'
        }).then((result) => {
          console.log(result?.message)
        })
      }
    }
  }
})

export function useTableSettingStore() {
  const _tableSettingStore = tableSettingStore(store)
  return _tableSettingStore
}
